package com.example.cd5160866.tabs.camera;

import android.Manifest;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.example.cd5160866.tabs.R;

import java.util.ArrayList;
import java.util.List;

import static android.os.Build.VERSION_CODES.M;

public class CameraActivity extends AppCompatActivity {

    private static int REQUEST_CODE_PERMISSION_CAMERA = 1;

    private SurfaceView surfaceView;

    public static List<Integer> cameras = new ArrayList<>();

    private Camera camera;

    private boolean hasOpened = false;

    private int lastWorkCameraId = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_main);
        intViewComponent();
        checkPermissionIfNeed();
        initCameras();
    }

    private void checkPermissionIfNeed() {
        if (android.os.Build.VERSION.SDK_INT >= M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION_CAMERA);
            }
        }
    }

    private void intViewComponent() {
        surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        ((SwitchCompat) findViewById(R.id.sc_change)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                open(cameras.get(isChecked ? 1 : 0));
            }
        });
        findViewById(R.id.btn_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                open(cameras.get(0));
            }
        });
        findViewById(R.id.btn_take).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });
        findViewById(R.id.focus).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                focus();
            }
        });
    }

    /**
     * 打开相机
     * Q 打开哪一个？
     */
    public void open(int cameraId) {
        release();
        lastWorkCameraId = cameraId;
        //                camera = Camera.open();
        camera = Camera.open(cameraId);
        //        camera.setPreviewCallback(new Camera.PreviewCallback() {
        //            @Override
        //            public void onPreviewFrame(byte[] data, Camera camera) {
        //                Log.d("qw", "onPreviewFrame data " + data.toString());
        //            }
        //        });
        startPreview(cameraId, surfaceView.getHolder());
        hasOpened = true;
    }

    /**
     * 拍照
     */
    public void takePhoto() {
        camera.takePicture(new Camera.ShutterCallback() {
            @Override
            public void onShutter() {
                Log.d("qw", "takeStart");
                Toast.makeText(getApplicationContext(), "开始拍照", Toast.LENGTH_SHORT).show();
            }
        }, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Log.d("qw", "onPictureTaken");
                Toast.makeText(getApplicationContext(), "正在保存照片...", Toast.LENGTH_SHORT).show();
                Utils.writeFile(data, Environment.getExternalStorageDirectory().getPath(), "ACamera1Photo.jpg");
                Toast.makeText(getApplicationContext(), "保存完成", Toast.LENGTH_SHORT).show();
                startPreview(lastWorkCameraId, surfaceView.getHolder());
            }
        });
    }

    /**
     * 初始化
     */
    public static void initCameras() {
        //有多少个摄像头
        int numberOfCameras = Camera.getNumberOfCameras();

        for (int i = 0; i < numberOfCameras; ++i) {
            final Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(i, cameraInfo);
            cameras.add(i);
        }
    }

    /**
     * 开启相机预览
     */
    private void startPreview(int currentCameraId, SurfaceHolder surfaceHolder) {
        try {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(currentCameraId, cameraInfo);

            //获取相机参数
            Camera.Parameters parameters = camera.getParameters();
            //自动对焦
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);

            List<Camera.Size> size = parameters.getSupportedPreviewSizes();
            //设置预览大小
//            parameters.setPreviewSize(size.get(5).width, size.get(5).height);
                        parameters.setPreviewSize(800, 480);
            //            parameters.setPictureSize(1080,1920);

            camera.setDisplayOrientation(90);
            //设置相机参数
            camera.setParameters(parameters);
            //设置surfaceHolder
            camera.setPreviewDisplay(surfaceHolder);
            //开启预览
            camera.startPreview();

        } catch (Exception ignore) {
            Log.d("qw", " camera error" + ignore.getMessage());
        }
    }

    private void focus() {
        if (null != camera) {
            Toast.makeText(getApplicationContext(), "正在对焦...", Toast.LENGTH_SHORT).show();
            camera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    Toast.makeText(getApplicationContext(), "对焦完成", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 释放资源
     */

    private void release() {
        try {
            if (null != camera) {
                camera.release();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, " 权限授予失败", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, " 权限授予成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasOpened && null != camera) {
            open(lastWorkCameraId);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }
}
